package org.wxy.sdk.base.impl;


import org.wxy.sdk.base.IBaseModel;
import org.wxy.sdk.base.IBasePresenter;
import org.wxy.sdk.base.IBaseView;

import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by wxy on 2018/05/27.
 *
 * @author wxy
 * @date on 2018/05/27 11:32
 */
public abstract class BasePresenterImpl<View extends IBaseView, Model extends IBaseModel> implements IBasePresenter {

    private CompositeSubscription mCompositeSubscription;

    protected View mView;
    protected Model mModel;

    public BasePresenterImpl(View view, Model model) {
        mView = view;
        mModel = model;
    }

    /**
     * 所有Model返回的Subscription都必须调用addSubscription(Subscription);
     * @param subscription Subscription
     */
    protected void addSubscription(Subscription subscription){
        if (this.mCompositeSubscription == null){
            mCompositeSubscription = new CompositeSubscription();
        }
        mCompositeSubscription.add(subscription);
    }

    /**
     * 生命周期结束时调用,取消正在处理的耗时任务.
     */
    @Override
    public void unsubscribe() {
        if (mCompositeSubscription != null){
            mCompositeSubscription.unsubscribe();
            mCompositeSubscription = null;
        }

        if (mModel != null) {
            mModel.destroy();
        }
        mModel = null;
        mView = null;
    }

    @Override
    public IBaseModel getModel() {
        return mModel;
    }

    public boolean isUnsubscribe() {
        return mCompositeSubscription != null && mCompositeSubscription.isUnsubscribed();
    }

    protected <T> void subscribe(Observable<T> observable, Action1<T> action1, Action1<Throwable> throwable) {
        Subscription subscription = observable.subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(action1, throwable);
        addSubscription(subscription);
    }

    protected <T> void subscribe(Observable<T> observable, Action1<T> action1){
        subscribe(observable, action1, new Action1<Throwable>() {
            @Override
            public void call(Throwable throwable) {
                throwable.printStackTrace();
            }
        });
    }
}
